<template>
  <div class="symptom-page">
    <div class="page-header">
      <h2>症状管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">新增症状</el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="症状分类">
          <el-select
            v-model="searchForm.category_id"
            placeholder="请选择分类"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="category in categoryList"
              :key="category.id"
              :label="getDisplayName(category, 'name')"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入症状名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />


        <!-- 症状分类 -->
        <el-table-column label="所属分类" width="150">
          <template #default="{ row }">
            <el-tag type="info">
              {{ getDisplayName(row, 'category_name') }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 多语言名称显示 -->
        <el-table-column label="症状名称" min-width="250">
          <template #default="{ row }">
            <div class="multilang-text">
              <div><strong>中文:</strong> {{ row.name_zh_cn }}</div>
              <div><strong>English:</strong> {{ row.name_en_us }}</div>
              <div><strong>日本語:</strong> {{ row.name_ja_jp }}</div>
              <div><strong>Беларуская:</strong> {{ row.name_be_by }}</div>
            </div>
          </template>
        </el-table-column>

        <!-- 分类名称 -->
        <el-table-column label="分类名称" width="150">
          <template #default="{ row }">
            <div class="category-name">
              <div><strong>中文:</strong> {{ row.category_name_zh_cn || '-' }}</div>
              <div><strong>English:</strong> {{ row.category_name_en_us || '-' }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="sort_order" label="排序" width="80" />

        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="创建时间" width="160" />

        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 批量操作 -->
    <div v-if="selectedRows.length > 0" class="batch-actions">
      <el-button type="danger" @click="handleBatchDelete">
        批量删除 ({{ selectedRows.length }})
      </el-button>
    </div>

    <!-- 表单弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="症状分类" prop="category_id">
              <el-select
                v-model="formData.category_id"
                placeholder="请选择症状分类"
                style="width: 100%"
              >
                <el-option
                  v-for="category in categoryList"
                  :key="category.id"
                  :label="getDisplayName(category, 'name')"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 多语言名称 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="中文名称" prop="name_zh_cn">
              <el-input v-model="formData.name_zh_cn" placeholder="请输入中文名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="英文名称" prop="name_en_us">
              <el-input v-model="formData.name_en_us" placeholder="Please enter English name" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="日文名称" prop="name_ja_jp">
              <el-input v-model="formData.name_ja_jp" placeholder="日本語名を入力してください" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="白俄语名称" prop="name_be_by">
              <el-input v-model="formData.name_be_by" placeholder="Увядзіце назву" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 多语言描述 -->
        <el-form-item label="中文描述">
          <el-input
            v-model="formData.description_zh_cn"
            type="textarea"
            :rows="2"
            placeholder="请输入中文描述"
          />
        </el-form-item>

        <el-form-item label="英文描述">
          <el-input
            v-model="formData.description_en_us"
            type="textarea"
            :rows="2"
            placeholder="Please enter English description"
          />
        </el-form-item>

        <el-form-item label="日文描述">
          <el-input
            v-model="formData.description_ja_jp"
            type="textarea"
            :rows="2"
            placeholder="日本語での説明を入力"
          />
        </el-form-item>

        <el-form-item label="白俄语描述">
          <el-input
            v-model="formData.description_be_by"
            type="textarea"
            :rows="2"
            placeholder="Увядзіце апісанне"
          />
        </el-form-item>

        <!-- 多语言关键词 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="中文关键词">
              <el-input
                v-model="formData.keywords_zh_cn"
                placeholder="中文关键词，逗号分隔"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="英文关键词">
              <el-input
                v-model="formData.keywords_en_us"
                placeholder="English keywords, comma separated"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="日文关键词">
              <el-input
                v-model="formData.keywords_ja_jp"
                placeholder="日本語キーワード、カンマ区切り"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="白俄语关键词">
              <el-input
                v-model="formData.keywords_be_by"
                placeholder="Ключавыя словы, праз коску"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" prop="sort_order">
              <el-input-number v-model="formData.sort_order" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="is_active">
              <el-switch 
                v-model="formData.is_active" 
                :active-value="1" 
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useLanguageStore } from '@/stores/language'
import { useApi } from '@/composables/useApi'

// 语言状态管理
const languageStore = useLanguageStore()
const { symptomApi, symptomCategoryApi } = useApi()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const tableData = ref([])
const selectedRows = ref([])
const categoryList = ref([])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  category_id: ''
})

// 分页
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 表单数据
const formData = reactive({
  id: null,
  category_id: '',
  name_zh_cn: '',
  name_en_us: '',
  name_ja_jp: '',
  name_be_by: '',
  description_zh_cn: '',
  description_en_us: '',
  description_ja_jp: '',
  description_be_by: '',
  keywords_zh_cn: '',
  keywords_en_us: '',
  keywords_ja_jp: '',
  keywords_be_by: '',
  sort_order: 0,
  is_active: 1
})

// 表单验证规则
const formRules = {
  category_id: [
    { required: true, message: '请选择症状分类', trigger: 'change' }
  ],
  name_zh_cn: [
    { required: true, message: '请输入中文名称', trigger: 'blur' }
  ],
  name_en_us: [
    { required: true, message: '请输入英文名称', trigger: 'blur' }
  ],
  name_ja_jp: [
    { required: true, message: '请输入日文名称', trigger: 'blur' }
  ],
  name_be_by: [
    { required: true, message: '请输入白俄语名称', trigger: 'blur' }
  ]
}

const formRef = ref()

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑症状' : '新增症状')

// 方法
const getDisplayName = (row, prefix) => {
  const currentLang = languageStore.currentLanguage
  const field = `${prefix}_${currentLang}`
  return row[field] || row[`${prefix}_zh_cn`] || ''
}

const getDisplayKeywords = (row) => {
  const currentLang = languageStore.currentLanguage
  const field = `keywords_${currentLang}`
  return row[field] || row.keywords_zh_cn || ''
}

const fetchCategoryList = async () => {
  try {
    const result = await symptomCategoryApi.getActiveList()
    if (result.code === 0) {
      categoryList.value = result.data
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      keyword: searchForm.keyword,
      category_id: searchForm.category_id
    }

    const result = await symptomApi.getList(params)

    if (result.code === 0) {
      tableData.value = result.data.list
      pagination.total = result.data.total
    } else {
      ElMessage.error(result.msg)
    }
  } catch (error) {
    ElMessage.error('请求失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

const handleReset = () => {
  searchForm.keyword = ''
  searchForm.category_id = ''
  pagination.page = 1
  fetchData()
}

const handlePageChange = (page) => {
  pagination.page = page
  fetchData()
}

const handleSizeChange = (size) => {
  pagination.limit = size
  pagination.page = 1
  fetchData()
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除症状 "${row.name_zh_cn}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const result = await symptomApi.delete(row.id)

      if (result.code === 0) {
        ElMessage.success('删除成功')
        fetchData()
      } else {
        ElMessage.error(result.msg)
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleBatchDelete = () => {
  const ids = selectedRows.value.map(row => row.id)

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 个症状吗？`,
    '确认批量删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const result = await symptomApi.batchDelete(ids)

      if (result.code === 0) {
        ElMessage.success('批量删除成功')
        selectedRows.value = []
        fetchData()
      } else {
        ElMessage.error(result.msg)
      }
    } catch (error) {
      ElMessage.error('批量删除失败')
    }
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return

  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return

  submitting.value = true

  try {
    const data = isEdit.value ? { ...formData, id: formData.id } : formData
    const result = isEdit.value
      ? await symptomApi.update(data)
      : await symptomApi.create(data)

    if (result.code === 0) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      fetchData()
    } else {
      ElMessage.error(result.msg)
    }
  } catch (error) {
    ElMessage.error('提交失败')
  } finally {
    submitting.value = false
  }
}

const handleDialogClose = () => {
  formRef.value?.resetFields()
  resetForm()
}

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    category_id: '',
    name_zh_cn: '',
    name_en_us: '',
    name_ja_jp: '',
    name_be_by: '',
    description_zh_cn: '',
    description_en_us: '',
    description_ja_jp: '',
    description_be_by: '',
    keywords_zh_cn: '',
    keywords_en_us: '',
    keywords_ja_jp: '',
    keywords_be_by: '',
    sort_order: 0,
    is_active: 1
  })
}

// 生命周期
onMounted(() => {
  fetchCategoryList()
  fetchData()
})
</script>

<style scoped>
.symptom-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.search-bar {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.multilang-text {
  line-height: 1.6;
}

.multilang-text div {
  margin-bottom: 4px;
}

.multilang-text div:last-child {
  margin-bottom: 0;
}

.keywords-text {
  color: #666;
  font-size: 12px;
  word-break: break-all;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.batch-actions {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: #fff;
  padding: 10px 20px;
  border-radius: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  z-index: 1000;
}

.dialog-footer {
  text-align: right;
}
</style>